// 当前选中的 协议
import type {Field, ProtocolItemDO} from "@/type/toolLibs/protocol";
import {ref, computed, reactive} from "vue";
import {getProtocolCategory} from "@/api/toolLibs/protocolLib";
import {message} from "@/utils/ElmessasgeUtils";
import router from "@/router";
export let baseField: Field = {
    name: '',
    fields: [
        {name: "dst", type: "u8", size: 1, description: "目的进程号"},
        {name: "src", type: "u8", size: 1, description: "源进程号"},
        {name: "bodyLen", type: "u16", size: 2, description: "消息体长度"},
        {name: "msgType", type: "u8", size: 1, description: "消息类型"}
    ],
    type: ''
}

export const currentProtocol = ref<ProtocolItemDO>({
    id: '',
    protocolName: '测试协议',

    createTime: '',
    createUserId: '',
    createUserName: '',
    createNickName: '',

    updateTime: '',
    updateUserId: '',
    updateUserName: '',
    updateNickName: '',
    protocolContent: baseField
});


// 搜索表单数据
export const searchForm = reactive({
    createTimeBegin: '',
    createTimeEnd: '',
    protocolName: '',
    createNickName: '',
    category: '0',
    categories: [],
    code: null,
    msgType: null,
});

// 从后端获取分类数据
export const categoriesFromBackend = ref([])

export const treeCategories = computed(() => {
    const categories = [...categoriesFromBackend.value];
    const map = new Map();
    const roots: any[] = [];

    // 添加"全部"分类作为根节点
    roots.push({
        id: '0',
        name: '全部',
        children: [],
        isAll: true
    });

    // 首先将所有分类放入映射表
    categories.forEach((category: any) => {
        map.set(category.id, {...category, children: []});
    });

    // 然后构建树形结构
    categories.forEach((category: any) => {
        const parent = map.get(category.pid);
        if (parent) {
            parent.children.push(map.get(category.id));
        } else if (category.pid === '0') {
            roots[0].children.push(map.get(category.id));
        }
    });

    return roots;
})

export function getCategoryName(category: string) {
    if (category == '0') {
        return '全部'
    }
    let res: any = categoriesFromBackend.value.find((c: any) => c.id == category);

    return res ? res.name : ''
}


// 更新全部命令类别列表
export async function updateCategoryList() {

    let mockCategories = [];
    // 使用模拟数据替换后端请求
    let res: any = await getProtocolCategory()

    if (res.data.code === 200) {
        mockCategories = res.data.data;
        mockCategories = mockCategories.filter((item: any) => item.id !== '0')
        categoriesFromBackend.value = mockCategories;
        console.log("从后端获取获取分类", categoriesFromBackend.value);
    } else {
        message('获取协议类别失败', 'error')
    }

}


/**
 * 打开解析器
 */
export async function handleOpenProtocolParse(protocolId: any) {

    await router.push({
        path: '/ToolLibs/ProtocolViewer/protocolParser',
        query: {
            protocolId: protocolId,
        }
    })
}

/**
 * 打开编辑器
 */
export async function handleOpenProtocolEdit(protocolId: any, flag: number = 0) {
    await router.push({
        path: '/ToolLibs/ProtocolViewer/protocolViewer',
        query: {
            model: flag,
            protocolId: protocolId,
        }
    })
}